define([
    'views/DiaryTableView',
    'views/DiaryFormView',
    'views/PageBarView',
    'models/Diary',
    'jquery',
    'underscore',
    'backbone'
], function(DiaryTableView, DiaryFormView, PageBarView, Diary) {

    var formView = new DiaryFormView();
    var tableView = new DiaryTableView();
    var pageBarView = new PageBarView();

    var AppRouter = Backbone.Router.extend({
        routes: {
            "diaries": "getDiaries",
            "diaries/:page": "getDiariesWithPage",
            "diary:id": "getDiary",
            "*actions": "defaultRoute"
        }
    });

    var initialize = function() {
        var app_router = new AppRouter;

        app_router.on('route:getDiaries', function() {
            showDiaryList(0);
        });

        app_router.on('route:getDiariesWithPage', function(page) {
            showDiaryList(page);
        });

        app_router.on('route:getDiary', function(id) {
            showDiary(id);
        });

        app_router.on('route:defaultRoute', function(actions) {
            showDiaryList(0);
        });

        Backbone.history.start();
        console.log("Backbone.history.started");
    };

    var showDiary = function(id) {
        console.log(id);
        var diary = new Diary();
        if (id === "new") {
            renderForm(diary);
        } else {
            diary.set({id: id});
            diary.fetch({
                success: function() {
                    renderForm(diary);
                },
                error: function(e) {
                    alert("error on fetch");
                    console.log("error on fetch");
                    console.log(e);
                }
            });
        }
    };

    var renderForm = function(diaryModel) {
        formView.model = diaryModel;
        formView.render();
    };

    var showDiaryList = function(page) {
        tableView.page = page;
        tableView.render();

        pageBarView.page = page;
        pageBarView.render();
    };


    return {
        initialize: initialize
    };
});
